package com.zk.server;

import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TomcatServer extends AbstractServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(TomcatServer.class);

    protected Tomcat tomcat;
    protected String host;
    protected int port;

    public TomcatServer(String host, int port) {
        this.host = host;
        this.port = port;
        this.tomcat = new Tomcat();
    }

    public void start() throws Exception {
        tomcat.setBaseDir(getTempDirectory().getAbsolutePath());

        // 绑定端口和地址
        Connector connector = new Connector("HTTP/1.1");
        connector.setPort(port);
        connector.setAttribute("address", host);
        tomcat.setConnector(connector);

        // 添加项目
        tomcat.addWebapp("/", getWebAppDirectory().getAbsolutePath());

        // 启动
        tomcat.start();
        LOGGER.info("start server at http://{}:{}", host, port);

        tomcat.getServer().await();
    }

    public void shutdown() throws Exception {
        if (tomcat != null) {
            tomcat.stop();
            tomcat.destroy();
            tomcat = null;
        }

        LOGGER.info("stop server");
    }

    ///

    public static void main(String...args) throws Exception {
        new TomcatServer("localhost", 9001).start();
    }

}